package sort;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO
 *
 * @author 司松坡
 * @createTime 2023年05月08日
 */
public class Sort {
    public static void main(String[] args) {
        int[] arr = {1, 33, 543, 2323,213132,12313,3124,543253255,65456, 12231, 55, 2, 55, 3, 21,};
        printArr(arr);
        //插入排序
        insertSort(arr);
        System.out.println("插入排序后结果：");
        printArr(arr);
        //冒泡排序
        arr = new int[]{1, 33, 543, 2323, 213132, 12313, 3124, 543253255, 65456, 12231, 55, 2, 55, 3, 21,};
        bubbleSort(arr);
        System.out.println("冒泡排序后结果：");
        printArr(arr);
        //选择排序
        arr = new int[]{1, 33, 543, 2323, 213132, 12313, 3124, 543253255, 65456, 12231, 55, 2, 55, 3, 21,};
        chooseSort(arr);
        System.out.println("选择排序后结果");
        printArr(arr);


    }

    static ExecutorService executor = Executors.newFixedThreadPool(3);

    /**
     * 插入排序
     */
    public static void insertSort(int[] arr){
        if (null == arr || arr.length < 2) {
            return;
        }
        int length = arr.length;
        executor.shutdown();
        for (int i = 1; i < length; i++) {
            if (arr[i] < arr[i-1]){
                for (int j = i; j >0 ; j--) {
                    if (arr[j] < arr[j-1]){
                        exchange(arr,j,j-1);
                    } else {
                        break;
                    }
                }
            }
        }
    }



    /**
     * 冒泡排序
     */
    public static void bubbleSort(int[] arr) {
        if (null == arr || arr.length < 2) {
            return;
        }
        int length = arr.length;
        for (int i = length ; i > 0; i--) {
            for (int j = 0; j < i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    exchange(arr, j, j + 1);
                }
            }
        }

    }


    /**
     * 选择排序
     */
    public static void chooseSort(int[] arr) {
        if (null == arr || arr.length < 2) {
            return;
        }
        int length = arr.length;
        for (int i = 0; i < length - 1; i++) {
            int min = i;
            for (int j = i + 1; j < length; j++) {
                if (arr[min] > arr[j]) {
                    min = j;
                }
            }
            if (i != min) {
                exchange(arr, i, min);
            }
        }
    }


    /**
     * @author 司松坡
     * @description 交换位置
     * @date 2023/5/8
     */
    public static void exchange(int[] arr, int i, int j) {
        int mid = arr[i];
        arr[i] = arr[j];
        arr[j] = mid;
    }

    /**
     * 打印数组
     */
    public static void printArr(int[] arr) {
        for (int i : arr) {
            System.out.print(i + "  ");
        }
        System.out.println();
    }





}
